<?php
namespace app\api\controller;
use think\facade\Request;
use think\facade\Db;
class Rank
{
    public function rankList()
    {
        $pageData = Request::param();
        $page = $pageData['page'] ?? 1;
        $perPage = $pageData['pageSize'] ?? 10;
        $keyword = $pageData['keyword'] ?? '';

        // 主查询：用户表，关联submission表统计提交数据
        $query = Db::name('user')
            ->alias('u')
            // 左连接submission表
            ->leftJoin('submission s', 'u.id = s.user_id')
            // 统计字段
            ->field('u.*, 
                    COUNT(s.id) as submission_count, 
                    COUNT(DISTINCT CASE WHEN s.status = 2 THEN s.problem_id END) as passed_count,
                    ROUND(
                        IFNULL(
                            COUNT(DISTINCT CASE WHEN s.status = 2 THEN s.problem_id END) / COUNT(s.id) * 100, 
                            0
                        ), 
                        2
                    ) as pass_rate')
            ->group('u.id'); // 按用户ID分组

        // 搜索条件
        if ($keyword) {
            $query = $query->where('u.username', 'like', '%'.$keyword.'%');
        }

        // 分页查询
        $data = $query->order('passed_count', 'desc') // 按通过题目数降序排序
                ->paginate([
                    'list_rows' => $perPage,
                    'page'      => $page,
                ]);

        return json([
            'message' => '数据查询成功',
            'code'    => 200,
            'data'    => $data,
        ]);
    }
}